import { useRef, useState, useEffect } from 'react'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { listen } from '@tauri-apps/api/event'
import { invoke } from '@tauri-apps/api/core'

const win = getCurrentWindow()
let timerId = null
let countdownId = null
const M = number => (number > 0 ? Math.floor(number) : Math.ceil(number))

function Clock() {
  const clockRef = useRef(null)

  const [time, setTime] = useState(new Date().toLocaleTimeString())
  const [fontSize, setFontSize] = useState('36px')
  const [fontColor, setFontColor] = useState('#FF4A58')
  const [fontStyle, setFontStyle] = useState('Helvetica')

  function listener(name, cb) {
    return listen(name, event => {
      console.log(`%c Line:20 🍢 ${name} =>`, 'color:#33a5ff', event)
      cb(event.payload.value)
    })
  }

  function timeStart() {
    timerId && timerId()
    const intervalId = setInterval(() => {
      setTime(new Date().toLocaleTimeString())
    }, 1000)
    return () => clearInterval(intervalId)
  }

  useEffect(() => {
    timerId = timeStart()
    const unlistenFontSize = listener('change-font-size', setFontSize)
    const unlistenFontColor = listener('change-font-color', setFontColor)
    const unlistenFontStyle = listener('change-font-family', setFontStyle)
    const unlistenCountdown = listener('change-countdown', handleCountdown)

    return () => {
      timerId && timerId()
      countdownId && countdownId()
      unlistenFontSize.then(fn => fn())
      unlistenFontColor.then(fn => fn())
      unlistenFontStyle.then(fn => fn())
      unlistenCountdown.then(fn => fn())
    }
  }, [])

  const handleMouseDown = async e => {
    await win.startDragging()
  }

  useEffect(() => {
    const offsetWidth = clockRef.current.offsetWidth + 16
    const offsetHeight = clockRef.current.offsetHeight + 16
    console.log('%c Line:63 🍋 offsetWidth', 'color:#f7b731', offsetWidth)
    console.log('%c Line:61 🍉 offsetHeight', 'color:#f7b731', offsetHeight)
    // 发送消息给主进程, 通知窗口大小变化
    setWinSize(offsetWidth, offsetHeight)
  }, [fontSize, fontStyle])

  async function setWinSize(x, y) {
    await invoke('set_win_size', { data: { width: x, height: y } })
  }

  const handleCountdown = minutes => {
    console.log('%c Line:45 🍎 minutes', 'color:#42b983', minutes)
    if (minutes === 0) {
      countdownId && countdownId() // 停止倒计时计时器
      timerId = timeStart() // 重新开始时间计时器
      return
    }
    // 如果倒计时已经存在, 停止倒计时计时器
    countdownId && countdownId()
    timerId && timerId()

    const endTime = new Date().getTime() + minutes * 1e3
    countdownId = countdownStart(endTime)
  }

  function countdownStart(endTime) {
    const intervalId = setInterval(() => {
      const now = new Date().getTime()
      const distance = endTime - now
      if (distance <= 0) {
        console.log('%c Line:83 🍷', 'color:#f5ce50', '倒计时结束')
      }
      const hours = M((distance % (1e3 * 60 * 60 * 24)) / (1e3 * 60 * 60))
      const minutes = M((distance % (1e3 * 60 * 60)) / (1e3 * 60))
      const seconds = M((distance % (1e3 * 60)) / 1e3)
      const h = String(hours).padStart(2, '0')
      const m = String(minutes).padStart(2, '0')
      const s = String(seconds).padStart(2, '0')
      const time = `${h}:${m}:${s}`
      console.log('%c Line:95 🥪 time', 'color:#93c0a4', time)
      setTime(time)
    }, 1000)
    return () => clearInterval(intervalId)
  }

  return (
    <div data-tauri-drag-region className="grid grid-cols-1 place-items-center">
      <div
        ref={clockRef}
        onMouseDown={handleMouseDown}
        style={{
          fontSize: fontSize,
          color: fontColor,
          fontFamily: fontStyle,
          fontWeight: '600',
          textAlign: 'center',
          cursor: 'default',
        }}>
        {time}
      </div>
    </div>
  )
}

export default Clock
